// $ sudo apt install libglew-dev
#include <GL/glew.h>

// $ sudo apt install libglfw3-dev
#include <GLFW/glfw3.h>

#include <iostream>

using namespace std;

#define numVAOS 1
GLuint renderingProgram;
GLuint vao[numVAOS];

GLuint createShaderProgram(){
    const char *vShaderSource = 
        "#version 430 \n"
        "void main(void) \n"
        "{ gl_Position = vec4(0.0, 0.0, 0.0, 1.0); }";
    const char *fShaderSource = 
        "#version 430 \n"
        "out vec4 color; \n"
        "void main(void) { \n"
        "   if(gl_FragCoord.x < 200) { \n"
        "       color = vec4(1.0, 0.0, 0.0, 1.0); \n"
        "   } else { \n"
        "       color = vec4(0.0, 0.0, 1.0, 1.0); \n"
        "   } \n"
        "}";
    GLuint vShader = glCreateShader(GL_VERTEX_SHADER);
    GLuint fShader = glCreateShader(GL_FRAGMENT_SHADER);

    glShaderSource(vShader, 1, &vShaderSource, NULL);
    glShaderSource(fShader, 1, &fShaderSource, NULL);
    glCompileShader(vShader);
    glCompileShader(fShader);

    GLuint vfProgram = glCreateProgram();
    glAttachShader(vfProgram, vShader);
    glAttachShader(vfProgram, fShader);
    glLinkProgram(vfProgram);

    return vfProgram;
}

void init(GLFWwindow *window) {
    renderingProgram = createShaderProgram();
    glGenVertexArrays(numVAOS, vao);
    glBindVertexArray(vao[0]);
}

void display(GLFWwindow *window, double currentTime){
    glUseProgram(renderingProgram);
    glPointSize(300);
    glDrawArrays(GL_POINTS, 0, 1);
}

int main(int, char**) {
    int ret = 0;

    std::cout << "Hello, world!\n";
    if(!(ret = glfwInit())) {
        cout << "glfwInit(1): " << ret << endl;
        exit(EXIT_FAILURE);
    }
    // 要求机器必须兼容OpenGL 4.3的版本
    glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 4);
    glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
    // 创建glfw窗口
    GLFWwindow *window = glfwCreateWindow(600, 600, "Chapter2 - program1", NULL, NULL);
    // 与当前OpenGL上下文关联起来
    glfwMakeContextCurrent(window);

    // 注意这里是glewInit(), 不是glfwInit()
    if((ret = glewInit()) != GLEW_OK) {
        cout << "glfwInit(2): " << ret << endl;
        exit(EXIT_FAILURE);
    }
    // 只要有1个buffer交换就刷新
    glfwSwapInterval(1);

    init(window);

    while(!glfwWindowShouldClose(window)) {
        display(window, glfwGetTime());
        // 垂直同步
        glfwSwapBuffers(window);
        glfwPollEvents();
    }

    glfwDestroyWindow(window);
    glfwTerminate();

    return EXIT_SUCCESS;
}